import { updateQueue } from './component';
// 统一代理事件绑定
function addEvent(dom, eventName, handler) {
  let store;
  if (dom.store) {
    store = dom.store;
  } else {
    store = dom.store = {};
  }
  store[eventName] = handler;
  // 事件统一绑定到document上
  if(!document[eventName]) {
    document[eventName] = dispatchEvent;
  }
}

function dispatchEvent(event) {
  let { target, type } = event;
  const eventName = `on${type}`;
  updateQueue.isBatchingUpdate = true;
  // 模拟事件冒泡
  while(target) {
    const synthesisEvent = createsynthesisEvent(event);
    const store = target.store;
    const handler = store && store[eventName];
    handler && handler.call(target, synthesisEvent)
    // 执行绑定的事件
    target = target.parentNode;
  }
  updateQueue.isBatchingUpdate = false;
  updateQueue.batchUpdate();
}

function createsynthesisEvent(event) {
  const synthesisEvent = {}
  for (let key in event) {
    synthesisEvent[key] = event[key];
  }
  return synthesisEvent;
}

export {
  addEvent,
}